大家好,今天跟大家一起學習如何在Visual Studio 2017 寫一個簡單的班表。
預計會分成三部分講解,大家敬請期待。
Step1 .建立專案
Step2.建立LocalDB
請參考:
在Visual Studio 2017 建立 localDB資料庫 (1/2)
在Visual Studio 2017 建立 localDB資料庫 (2/2)
Ste3. Using 使用的套件
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Step4. 寫撈出本週的方法
/********************/
/* Function* /
/********************/
public string[] Get_Week_List() //撈本週的日期
{
string[] re_arr = { "", "", "", "", "", "", "", "" };
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(strConnString);
cmd.Connection = conn;
DataTable dt = new DataTable();
string sqlStr = @"
select
convert(varchar,DATEADD(week, DATEDIFF(week, '', getDate()), ''), 111) as 'w1',
convert(varchar,DATEADD(day, +1, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w2',
convert(varchar,DATEADD(day, +2, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w3',
convert(varchar,DATEADD(day, +3, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w4',
convert(varchar,DATEADD(day, +4, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w5',
convert(varchar,DATEADD(day, +5, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w6',
convert(varchar,DATEADD(day, -1, DATEADD(week, DATEDIFF(week, '', getDate()), '')),111) as 'w7',
'0' as 'diffweek'
";
conn.Open();
cmd.CommandText = sqlStr;
SqlDataReader sread = cmd.ExecuteReader();
if (sread.HasRows)
{
while (sread.Read())
{
re_arr[0] = sread["w1"].ToString();
re_arr[1] = sread["w2"].ToString();
re_arr[2] = sread["w3"].ToString();
re_arr[3] = sread["w4"].ToString();
re_arr[4] = sread["w5"].ToString();
re_arr[5] = sread["w6"].ToString();
re_arr[6] = sread["w7"].ToString();
re_arr[7] = sread["diffweek"].ToString();
}
}
cmd.Dispose();
conn.Dispose();
return re_arr;
}
Step5. 寫一個顯示頁面
public ActionResult ShowWeek()
{
string[] week = Get_Week_List();
ViewBag.w1 = week[0];
ViewBag.w2 = week[1];
ViewBag.w3 = week[2];
ViewBag.w4 = week[3];
ViewBag.w5 = week[4];
ViewBag.w6 = week[5];
ViewBag.w7 = week[6];
return View();
}
Step 6. 顯示畫面(http://localhost:1501/Home/ShowWeek) 1501:為隨機的數字 請自行帶入數字
View的程式碼:
@{
ViewBag.Title = "ShowWeek";
}
<h2>ShowWeek</h2>
星期一: @ViewBag.w1<br />
星期二:@ViewBag.w2<br />
星期三:@ViewBag.w3<br />
星期四:@ViewBag.w4<br />
星期五:@ViewBag.w5<br />
星期六:@ViewBag.w6<br />
星期日:@ViewBag.w7<br />